import React, { useEffect, useState } from 'react';
import { Button, Spin } from 'antd';
import { getUrlParam } from '@/utils/index';
import { getTemplateById, updateTemplate, getBusiness, upsert } from '@/service/templateManager';
import GC from '@grapecity/spread-sheets';
import '@grapecity/spread-sheets-resources-zh';
import { getTestEditLicense } from '@/utils/license';

GC.Spread.Sheets.LicenseKey = process.env.REACT_APP_EDIT_KEY || getTestEditLicense();
GC.Spread.Common.CultureManager.culture('zh-cn');
import { SpreadSheets, Worksheet } from '@grapecity/spread-sheets-react';
import './index.less';

function EditSheet(props: any) {
    const [spread, setSpread] = useState<any>('');
    const [businessId, setBusinessId] = useState('');
    const [loadingFlag, setLoadingFlag] = useState(false);
    const [bindInfos, setBindInfos] = useState<any>('');
    const [templateInfo, setTemplateInfo] = useState<any>({});
    const [activeChange, setActionChange] = useState(true);
    let initSpread = function (value: any) {
        setSpread(value);
    };
    const getTemplate = async (id: string) => {
        setLoadingFlag(true);
        const data = await getTemplateById({ templateId: id });
        setLoadingFlag(false);
        if (data.data.data) {
            const info = data.data.data;
            const bindInfo = JSON.parse(info.bindInfo);
            setBindInfos(bindInfo);
            // @ts-ignore
            let spread = GC.Spread.Sheets.findControl(document.getElementsByClassName('container'));
            spread.suspendPaint();
            spread.fromJSON(JSON.parse(info.sheetInfo ? info.sheetInfo : '{ }'));
            spread.resumePaint();
            let sheet = spread.getActiveSheet();
            let sheetStyle = sheet.getDefaultStyle();
            // 修改并设置表的默认样式 locked 为 false.
            sheetStyle.locked = false;
            sheet.setDefaultStyle(sheetStyle);
            // 设置某一具体单元格 locked 为true
            const rowCount = sheet.getRowCount();
            const colCount = sheet.getColumnCount();
            for (let i = 0; i < rowCount; i++) {
                for (let a = 0; a < colCount; a++) {
                    sheet.getCell(Number(i), Number(a)).locked(false);
                }
            }
            const sheetName = sheet.name();
            if (bindInfo) {
                if (bindInfo[sheetName]) {
                    Object.keys(bindInfo[sheetName]).forEach((item: any) => {
                        // eslint-disable-next-line max-nested-callbacks
                        Object.keys(bindInfo[sheetName][item]).forEach((el: any) => {
                            const readOnly = bindInfo[sheetName][item][el].readOnly
                                ? bindInfo[sheetName][item][el]?.readOnly
                                : false;
                            sheet.getCell(Number(item), Number(el)).locked(readOnly);
                        });
                    });
                }
            }
            let customers = {
                sheet1: {
                    // sheet名称
                    '2': {
                        // 行
                        '2': {
                            // 列
                            value: '单元格内容1', // 单元格数据
                        },
                    },
                    '6': {
                        '5': {
                            value: '单元格内容2',
                        },
                    },
                },
                sheet2: {
                    // sheet名称
                    '1': {
                        // 行
                        '2': {
                            // 列
                            value: '单元格内容1', // 单元格数据
                        },
                    },
                    '2': {
                        '3': {
                            value: '单元格内容2',
                        },
                    },
                },
            };
            let options = {
                allowSelectLockedCells: true,
                allowSelectUnlockedCells: true,
                allowFilter: true,
                allowSort: true,
                allowResizeRows: true,
                allowResizeColumns: true,
                allowEditObjects: true,
                allowOutlineColumns: true,
                allowOutlineRows: true,
            };
            sheet.options.protectionOptions = options;
            sheet.options.isProtected = true;
            setTemplateInfo(data.data.data);
        }
    };
    const getBusinessInfo = async () => {
        const data = await getBusiness({ businessId: '11406286760368273139' });
        if (data.data.msg === 'success') {
            // @ts-ignore
            let spread = GC.Spread.Sheets.findControl(document.getElementsByClassName('container'));
            let sheet = spread.getActiveSheet();
            sheet.setDataSource(data.data.data ? JSON.parse(data.data.data.datas) : []);
            // setBusinessId(data.data.data.businessId);
            let defaultStyle = new GC.Spread.Sheets.Style();
            defaultStyle.locked = false;
            sheet.setDefaultStyle(defaultStyle, GC.Spread.Sheets.SheetArea.viewport);
            let options = {
                allowSelectLockedCells: true,
                allowSelectUnlockedCells: true,
                allowFilter: true,
                allowSort: true,
                allowResizeRows: true,
                allowResizeColumns: true,
                allowEditObjects: true,
                allowOutlineColumns: true,
                allowOutlineRows: true,
            };
            sheet.options.protectionOptions = options;
            sheet.options.isProtected = true;
        }
    };
    useEffect(() => {
        // eslint-disable-next-line react-hooks/rules-of-hooks
        const { templateId = '' } = getUrlParam();
        getTemplate(templateId);
        // getBusinessInfo();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    useEffect(() => {
        // sheet页切换事件
        // @ts-ignore
        let spread = GC.Spread.Sheets.findControl(document.getElementsByClassName('container'));
        let sheet = spread.getActiveSheet();
        let sheetStyle = sheet.getDefaultStyle();
        // 修改并设置表的默认样式 locked 为 false.
        sheetStyle.locked = false;
        sheet.setDefaultStyle(sheetStyle);
        const rowCount = sheet.getRowCount();
        const colCount = sheet.getColumnCount();
        for (let i = 0; i < rowCount; i++) {
            for (let a = 0; a < colCount; a++) {
                sheet.getCell(Number(i), Number(a)).locked(false);
            }
        }
        // 设置某一具体单元格 locked 为true
        // 设置表单保护
        const sheetName = sheet.name();
        if (bindInfos) {
            if (bindInfos[sheetName]) {
                Object.keys(bindInfos[sheetName]).forEach((item: any) => {
                    // eslint-disable-next-line max-nested-callbacks
                    Object.keys(bindInfos[sheetName][item]).forEach((el: any) => {
                        const readOnly = bindInfos[sheetName][item][el].readOnly
                            ? bindInfos[sheetName][item][el]?.readOnly
                            : false;
                        sheet.getCell(Number(item), Number(el)).locked(readOnly);
                    });
                });
            }
            sheet.options.isProtected = true;
        }

        spread.bind(GC.Spread.Sheets.Events.SheetTabClick, (e: any, info: any) => {
            setActionChange(!activeChange);
        });
        return () => {
            spread.unbind(GC.Spread.Sheets.Events.SheetTabClick);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [activeChange]);
    const handleCommit = async () => {
        const { templateId = '' } = getUrlParam();
        // eslint-disable-next-line no-var
        // @ts-ignore
        let sheet = spread.getActiveSheet();
        const datas = sheet.getDataSource();
        let customers = [
            { ID: 121, Name: 'A', Info1: 'Info0' },
            { ID: 100, Name: 'B', Info1: 'Info1' },
            {},
            { ID: 288, Name: 'C', Info1: 'Info2' },
        ];
        const data = await upsert({
            businessId: '11406286760368273139',
            templateId,
            datas: JSON.stringify(customers),
        });
        // if (sheet.hasPendingChanges()) {
        //     // 暂停绘制，事件，脏
        //     sheet.suspendPaint();
        //     sheet.suspendEvent();
        //     sheet.suspendDirty();
        //     // @ts-ignore
        //     // 将脏单元格信息存储在dirtyCells变量中
        //     let dirtyCells = sheet.getDirtyCells();
        //     console.log(dirtyCells, '脏数据');
        //     // 恢复绘制，事件，脏
        //     sheet.resumeDirty();
        //     sheet.resumeEvent();
        //     sheet.resumePaint();
        // }
        // const jsons = spread.toJSON();
        // console.log(jsons, 'jsons');
        // const data = await updateTemplate({
        //     name: templateInfo.name,
        //     templateId: templateInfo.templateId,
        //     sheetInfo: JSON.stringify(jsons),
        // });
    };
    return (
        <div className="edit_main">
            <div className="header_title">
                <span className="template_name">{templateInfo.name ? templateInfo.name : ''}</span>
                <div>
                    {/* <Button>暂存</Button> */}
                    <Button type="primary" onClick={() => handleCommit()}>
                        提交
                    </Button>
                </div>
            </div>
            <div className="sample-spreadsheets">
                <SpreadSheets workbookInitialized={(spread) => initSpread(spread)}>
                    <Worksheet />
                </SpreadSheets>
            </div>
            {loadingFlag && (
                <div className="loadding">
                    <Spin size="large" />
                </div>
            )}
        </div>
    );
}

export default EditSheet;
